<template>
  <div>
    <div class="jsoneditor-vue"></div>
    <div class="jsoneditor-btns" v-if="showBtns !== false">
      <button
        class="json-save-btn"
        type="button"
        @click="onSave()"
        :disabled="error"
      >
        {{ locale[lang].save }}
      </button>
    </div>
  </div>
</template>

<script>
import "./assets/jsoneditor.css";
import JsonEditor from "./assets/jsoneditor";
import { reactive, toRefs, getCurrentInstance } from "vue";
export default {
  name: "",
  props: {
    value: [String, Number, Object, Array],
    showBtns: [Boolean],
    expandedOnStart: {
      type: Boolean,
      default: false,
    },
    mode: {
      type: String,
      default: "tree",
    },
    modes: {
      type: Array,
      default: function () {
        return ["tree", "code", "form", "text", "view"];
      },
    },
    lang: {
      type: String,
      default: "zh",
    },
  },
  setup(props, { emit }) {
    const state = reactive({
      editor: null,
      error: false,
      json: this.value,
      internalChange: false,
      expandedModes: ["tree", "view", "form"],
      locale: {
        it: {
          save: "SALVA",
        },
        en: {
          save: "SAVE",
        },
        zh: {
          save: "保存",
        },
      },
    });

    let self = getCurrentInstance().proxy;

    let options = {
      mode: self.mode,
      modes: self.modes, // allowed modes
      onChange() {
        try {
          let json = self.editor.get();
          self.json = json;
          self.error = false;
          emit("json-change", json);
          self.internalChange = true;
          emit("input", json);
          self.$nextTick(function () {
            self.internalChange = false;
          });
        } catch (e) {
          self.error = true;
          emit("has-error", e);
        }
      },
      onModeChange() {
        self.expandAll();
      },
    };

    self.editor = new JsonEditor(
      self.$el.querySelector(".jsoneditor-vue"),
      options,
      self.json
    );

    return {
      ...toRefs(state),
      expandAll() {
        if (
          self.expandedOnStart &&
          self.expandedModes.includes(self.editor.getMode())
        ) {
          self.editor.expandAll();
        }
      },

      onSave() {
        self.$emit("json-save", self.json);
      },

      setEditor(value) {
        if (self.editor) self.editor.set(value);
      },
    };
  },
};
</script>
